package com.jiashihui.web.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jiashihui
 * @describe: 过滤器
 * @date 2019/01/07
 * 过滤器不在启动类扫描范围时，需要注意的是在启动类需要添加@ServletComponentScan扫描，其中包名自定义 @ServletComponentScan(basePackages = {"com.example.controller.filter"})
 */
@Component
@WebFilter(urlPatterns = "/test/*", filterName = "myFilter")
@Order(1)//@Order标记定义了组件的加载顺序
public class MyFilter implements Filter {

    private String name;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 对request、response进行一些预处理
        // request.setCharacterEncoding("UTF-8");
        // response.setCharacterEncoding("UTF-8");
        // response.setContentType("text/html;charset=UTF-8");
        System.out.println("----调用service之前执行一段代码----");
        // 执行目标资源，放行
        filterChain.doFilter(request, response);
        System.out.println("----调用service之后执行一段代码----");
    }
    public void init(FilterConfig filterConfig) {
        name = filterConfig.getInitParameter("name");
        System.out.println("----Filter初始化----" + name);
    }
    public void destroy() {
        System.out.println("----Filter销毁----");
    }
}
